﻿using System.Collections.Generic;
using System.IO;
using System.Xml;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.HtmlControls.Generics;

namespace Jayden.Dll.Web.Controls
{
	public class PhotoGalleryDiv : Div
	{
		private Ul m_Photos;

		public string ServerPath { get { return GetServerAttribute("path"); } set { SetServerAttribute("path", value); } }

		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);

			m_Photos = GetElementByServerId<Ul>("photos");
		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			string path = context.MapPath(ServerPath);
			string basePath = context.MapPath("/");
			basePath = basePath.Substring(0, basePath.Length - 1);
			if (Directory.Exists(path))
			{
				XmlDocument description = null;
				if(File.Exists(path + "\\descriptions.xml"))
				{
					description = new XmlDocument();
					description.Load(path + "\\descriptions.xml");
				}
				HashSet<string> imagesExtension = new HashSet<string>(new string[] { ".jpg", ".jpeg", ".png", ".gif"});
				string[] files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
				foreach (string file in files)
				{
					if (imagesExtension.Contains(Path.GetExtension(file).ToLowerInvariant()))
					{
						string imgSrc = file.Substring(basePath.Length).Replace("\\", "/");
						Li li = m_Photos.AddLi();
						Figure figure = li.AddControl<Figure>();
						A a = figure.AddA(null, imgSrc);
						Img img = a.AddImg(string.Empty, imgSrc + "?maxWidth=96&maxHeight=96&greyscale=true");
						if (description != null)
						{
							XmlElement element = description.DocumentElement.SelectSingleNode("img[@src=\"" + imgSrc + "\"]") as XmlElement;
							if (element != null)
							{
								XmlAttribute alt = element.Attributes["alt"];
								XmlAttribute title = element.Attributes["title"];
								XmlElement caption = element.SelectSingleNode("figcaption") as XmlElement;
								if (alt != null)
									img.Alt = alt.Value;
								if (title != null)
									img.Title = title.Value;
								if (caption != null)
								{
									FigCaption figcaption = HtmlControl.LoadControl(caption, context.ControlLoader) as FigCaption;
									figure.AddControl(figcaption);
								}
							}
						}
					}
				}
			}

			base.ProcessHtmlRequest(context);
		}
	}
}
